package com.fengycx.mq.consumer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fengycx.constants.Constants;
import com.fengycx.diyevents.PayOrderEvent;
import com.fengycx.pojo.domain.PayOrder;
import com.fengycx.service.IPayOrderService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@RocketMQMessageListener(
        consumerGroup = "order-to-pay-group",
        topic = "order-topic",
        selectorExpression = "order-to-pay-tag"
)
@Component
public class PayOrderConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;


    @Override
    public void onMessage(MessageExt message) {
        byte[] messageBody = message.getBody();
        String msgStr = new String(messageBody, StandardCharsets.UTF_8);
        //加个判断，判断payOrder是否已存在 TODO

        JSONObject msgObj = JSONUtil.parseObj(msgStr);
        PayOrder payOrder = BeanUtil.copyProperties(msgObj, PayOrder.class);
        Date date = new Date();
        payOrder.setCreateTime(date);
        payOrder.setSubject("风云出行");
        payOrder.setPayStatus(Constants.Order.UNPAID);
        //将现在的时间格式转化为202403211400
        String dateFormat = DateFormatUtils.format(date, "yyyyMMddHHmm");
        payOrder.setPayOrderNo(dateFormat+ "-"+ IdUtil.getSnowflakeNextId());
        payOrderService.save(payOrder);

        //创建自定义事件，监听器监听自定义的事件——目的是发送个推消息
        JSONObject entries = new JSONObject();
        entries.putOpt("orderNo",payOrder.getOrderNo());
        entries.putOpt("payUserId",payOrder.getPayUserId());
        //这里的参数必填，并且参数是监听器里面执行代码逻辑传入的参数
        applicationEventPublisher.publishEvent(new PayOrderEvent(entries));

    }
}
